package com.zr0726.news.web;

import com.zr0726.news.po.Comment;
import com.zr0726.news.po.User;
import com.zr0726.news.service.CommentService;
import com.zr0726.news.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

@Controller
public class CommentController {

    private String userAvatar = "https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1654409480,2232044795&fm=26&gp=0.jpg";
    private String adminAvatar = "https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2034740944,4251903193&fm=26&gp=0.jpg";

    @Autowired
    private CommentService commentService;

    @Autowired
    private NewsService newsService;

    @GetMapping("/comments/{newsId}")
    public String comments(@PathVariable Long newsId, Model model){
        model.addAttribute("comments", commentService.listCommentsByNewsId(newsId));
        return "new::commentList";
    }

    @PostMapping("/comments")
    public String post(Comment comment, HttpSession session){
        Long newsId = comment.getNews().getId();
        comment.setNews(newsService.getNews(newsId));
        User user = (User) session.getAttribute("user");
        if(user != null){
            comment.setAdminComment(true);
            comment.setAvatar(adminAvatar);
        }else{
            comment.setAvatar(userAvatar);
        }
        commentService.saveComment(comment);
        return "redirect:/comments/" + newsId;
    }

}
